package com.usth.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.bcd.tools.DBUtils;
import com.usth.model.Roles;
import com.usth.model.User;

public class UserDaoImpl extends HibernateDaoSupport implements IUserDao {

	public boolean regist(User user) {
		try {
			this.getHibernateTemplate().save(user);
		} catch (DataAccessException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public User userlogin(User user) {
		List<User> li=(List<User>) this.getHibernateTemplate().find("from User where userName=? and userPwd=?",new String[]{user.getUserName(),user.getUserPwd()});
		if(li.size()!=0){
			return li.get(0);
		}else{
			return null;
		}
		
	}

	public List<User> ulist() {
		List<User> list=this.getHibernateTemplate().find("from User");
		return list;
	}

	public List<Roles> rolelist() {
		List<Roles> list=this.getHibernateTemplate().find("from Roles");
		return list;
	}

	public void userrole(User u) {
		Connection con=DBUtils.getconnection();
		try {
			PreparedStatement pst=con.prepareStatement("update user set role_id=? where user_id=?");
			pst.setInt(1, u.getRoleId());
			pst.setInt(2, u.getUserId());
			pst.execute();
			pst.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void userupdate(User u) {
		this.getHibernateTemplate().update(u);
	}

}
